package com.agileai.miscdp.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

import de.hunsicker.jalopy.Jalopy;

public class JavaFormater {
	static Jalopy jalopy = null;

	private void init() throws IOException {
		try {
			URL convention = JavaFormater.class.getResource("convention.xml");
			Jalopy.setConvention(convention);
			jalopy = new Jalopy();
		} catch (IOException e) {
			throw e;
		}
	}

	public boolean format(File file,String encoding) throws IOException {
		boolean result = false;
		if (jalopy == null){
			init();			
		}
		try {
			String name = file.getName();
			if (name.endsWith(".java")) {
				jalopy.setEncoding(encoding);
				jalopy.setInput(file);
				jalopy.setOutput(file);
				result = jalopy.format();
			}
		} catch (FileNotFoundException e) {
			throw new IOException(e.getMessage());
		}
		return result;
	}

	public boolean format(String fileName,String encoding) throws IOException {
		boolean result = false;
		if (jalopy == null){
			init();
		}
		if (fileName == null){
			throw new IOException("fileName is null !");
		}
		if (!fileName.endsWith(".java")){
			throw new IOException(fileName + " is not ended with .java !");
		}
		File file = new File(fileName);
		if (!file.exists()){
			throw new FileNotFoundException(fileName + " is not exist!");			
		}
		try {
			jalopy.setEncoding(encoding);
			jalopy.setInput(file);
			jalopy.setOutput(file);
			result = jalopy.format();
		} catch (FileNotFoundException e) {
			throw e;
		}
		return result;
	}
}
